<script setup lang="ts">
defineOptions({
  name: "fabBoardWorkbench"
});

import { ref, nextTick, inject, watch } from "vue";
import { PxMessage } from "px-ui";
import { Rollback } from "@px-ui/icons-vue";
import fabBoardModelBox from "../fabBoardModelBox.vue";
import fabBoardEchartsModelBoxItem from "../fabBoardEchartsModelBoxItem.vue";
import {
  getFabBoardCountData,
  getFabBoardStatusData,
  getFabBoardPMTaskData,
  getFabBoardMaintainTaskData,
  getFabBoardAlarmData
} from "@/api/modules/fab";
import { storageLocal } from "@pureadmin/utils";
import { useRouterStoreHook } from "@/store/modules/router";

const routerStore = useRouterStoreHook();

const emitBoardAreaEventCb = inject("emitBoardAreaEvent") as Function;
const emitBoardClassEventCb = inject("emitBoardClassEvent") as Function;
const showAllDataCb = inject("showAllData") as Function;

const module_height = inject("moduleHeight", ref<string>(""));

// 是否重置 reset
const props = withDefaults(defineProps<{ reset: boolean }>(), { reset: false });

const title = ref<string>("机台信息");
// const area = ref<string>("");
const area = inject("area", ref<string>(""));
const loading = ref<boolean>(false);

const workbenchCountRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const workbenchStatusRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const workbenchPMTaskRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const workbenchMaintainTaskRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const workbenchAlarmRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);

const workbenchCountData = ref<Record<string, any> | null>(null);
const workbenchStatusData = ref<Record<string, any> | null>(null);
const workbenchPMTaskData = ref<Record<string, any> | null>(null);
const workbenchMaintainTaskData = ref<Record<string, any> | null>(null);
const workbenchAlarmData = ref<Record<string, any> | null>(null);

const workbenchCountTitle = ref<string>("各科关联机台数量");
const workbenchStatusTitle = ref<string>("今日机台状态统计");
const workbenchPMTaskTitle = ref<string>("今日机台保养任务");
const workbenchMaintainTaskTitle = ref<string>("今日机台维修任务");
const workbenchAlarmTitle = ref<string>("今日机台异常告警");

const classLabel = ref<string>("");
const isShowRollback = ref<boolean>(false);

const startLoading = () => {
  loading.value = true;
};

const closeLoading = () => {
  loading.value = false;
};

const areaChangeHandler = async (val: string, flag: boolean = false) => {
  emitBoardAreaEventCb("workbench", val);
  workbenchCountData.value = null;
  workbenchStatusData.value = null;
  workbenchPMTaskData.value = null;
  workbenchMaintainTaskData.value = null;
  workbenchAlarmData.value = null;
  await nextTick();
  classLabel.value = "";
  isShowRollback.value = false;
  await init(flag);
};

const getParams = (classCode?: string) => {
  const areaCode = area.value === "ALL" ? null : area.value;
  const params = { areaCode };
  classCode && (params["classCode"] = classCode);
  return params;
};

const queryFabCountDataFn = async (cb?: () => void) => {
  const params = getParams();
  workbenchCountRef.value.loading = true;
  const res = await getFabBoardCountData(params, () => {
    workbenchCountRef.value.loading = false;
  });
  workbenchCountData.value = res;
  cb && cb();
};

const queryFabStatusDataFn = async (cb?: () => void, classCode?: string) => {
  const params = getParams(classCode);
  workbenchStatusRef.value.loading = true;
  const res = await getFabBoardStatusData(params, () => {
    workbenchStatusRef.value.loading = false;
  });
  workbenchStatusData.value = res;
  cb && cb();
};

const queryFabPMTaskDataFn = async (cb?: () => void, classCode?: string) => {
  const params = getParams(classCode);
  workbenchPMTaskRef.value.loading = true;
  const res = await getFabBoardPMTaskData(params, () => {
    workbenchPMTaskRef.value.loading = false;
  });
  workbenchPMTaskData.value = res;
  cb && cb();
};

const queryFabMaintainTaskDataFn = async (cb?: () => void, classCode?: string) => {
  const params = getParams(classCode);
  workbenchMaintainTaskRef.value.loading = true;
  const res = await getFabBoardMaintainTaskData(params, () => {
    workbenchMaintainTaskRef.value.loading = false;
  });
  workbenchMaintainTaskData.value = res;
  cb && cb();
};

const queryFabAlarmDataFn = async (cb?: () => void, classCode?: string) => {
  const params = getParams(classCode);
  workbenchAlarmRef.value.loading = true;
  const res = await getFabBoardAlarmData(params, () => {
    workbenchAlarmRef.value.loading = false;
  });
  workbenchAlarmData.value = res;
  cb && cb();
};

const dataIndex = ref<number>(undefined);

const showAllData = async () => {
  const ec = await workbenchCountRef.value.el?.getEcharts();
  ec?.getInstance().dispatchAction({
    type: "unselect",
    dataIndex: [dataIndex.value]
  });
  workbenchCountRef.value?.barDataIndexArr?.splice(0);
  emitBoardClassEventCb("");
  startLoading();
  queryFabStatusDataFn(async () => {
    setTimeout(() => {
      workbenchStatusRef.value?.init(false, true);
    }, 0);
  });
  queryFabPMTaskDataFn(async () => {
    setTimeout(() => {
      workbenchPMTaskRef.value?.init(false, true);
    }, 0);
  });
  queryFabMaintainTaskDataFn(async () => {
    setTimeout(() => {
      workbenchMaintainTaskRef.value?.init(false, true);
    }, 0);
  });
  queryFabAlarmDataFn(async () => {
    setTimeout(() => {
      workbenchAlarmRef.value?.init(false, true);
    }, 0);
  });
  closeLoading();
  PxMessage({
    message: `已切换到全部数据`,
    type: "success"
  });
  isShowRollback.value = false;
  classLabel.value = "";
};

const init = async (flag: boolean = false) => {
  startLoading();
  await nextTick();
  queryFabCountDataFn(async () => {
    await nextTick();
    workbenchCountRef.value?.init(flag, true, true, (params?: any, flag?: boolean) => {
      if (flag) {
        showAllDataCb();
      } else {
        startLoading();
        const {
          data: { classCode = "", className = "" }
        } = params;
        dataIndex.value = params.dataIndex;
        emitBoardClassEventCb(classCode, className);
        isShowRollback.value = true;
        classLabel.value = className;
        queryFabStatusDataFn(async () => {
          setTimeout(() => {
            workbenchStatusRef.value?.init(false, true);
          }, 0);
        }, classCode);
        queryFabPMTaskDataFn(async () => {
          setTimeout(() => {
            workbenchPMTaskRef.value?.init(false, true);
          }, 0);
        }, classCode);
        queryFabMaintainTaskDataFn(async () => {
          setTimeout(() => {
            workbenchMaintainTaskRef.value?.init(false, true);
          }, 0);
        }, classCode);
        queryFabAlarmDataFn(async () => {
          setTimeout(() => {
            workbenchAlarmRef.value?.init(false, true);
          }, 0);
        }, classCode);
        closeLoading();
        PxMessage({
          message: `已切换到${className}数据`,
          type: "success"
        });
      }
    });
  });

  // 获取当前账号对应的科室，展示对应科室的数据
  let className = routerStore.getClassName;
  let classCode = "";
  if (className) {
    switch (className) {
      case "ADMIN":
        classCode = "";
        className = "";
        break;
      case "WATER":
        classCode = className;
        className = "水科";
        break;
      case "ELECTRICTITY":
        classCode = className;
        className = "电科";
        break;
      case "GAS":
        classCode = className;
        className = "气化科";
        break;
      case "MACHINE":
        classCode = className;
        className = "机械科";
        break;
      default:
        classCode = "";
        className = "";
        break;
    }
  }
  // 调试
  // classCode = "ELECTRICTITY";
  // className = "电科";

  // 现在默认展示全部科室
  classCode = "";
  className = "";
  isShowRollback.value = !!classCode;
  classLabel.value = className;
  queryFabStatusDataFn(async () => {
    setTimeout(() => {
      workbenchStatusRef.value.init(flag, true);
    }, 0);
  }, classCode);
  queryFabPMTaskDataFn(async () => {
    setTimeout(() => {
      workbenchPMTaskRef.value.init(flag, true);
    }, 0);
  }, classCode);
  queryFabMaintainTaskDataFn(async () => {
    setTimeout(() => {
      workbenchMaintainTaskRef.value.init(flag, true);
    }, 0);
  }, classCode);
  queryFabAlarmDataFn(async () => {
    setTimeout(() => {
      workbenchAlarmRef.value.init(flag, true);
    }, 0);
  }, classCode);
  closeLoading();
};

let flag: boolean = true;

watch(
  () => area.value,
  async val => {
    await nextTick();
    if (!flag) {
      val && (await areaChangeHandler(val, flag));
    } else {
      if (!!val) {
        await areaChangeHandler(val, flag);
        flag = false;
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
);

watch(
  () => props.reset,
  val => {
    if (props.reset) {
      showAllData();
    }
  }
);
</script>

<template>
  <!-- <fabBoardModelBox v-model="area" v-model:loading="loading" :title="title" @change="areaChangeHandler"> -->
  <!-- <template #extraTitle>
      <div v-if="isShowRollback" style="display: flex; align-items: center">
        <span style="font-size: 13px; line-height: 1; color: #555">{{ classLabel }}</span>
        <px-tooltip content="全部科室数据">
          <px-button type="primary" plain text size="large" :icon="Rollback" @click="showAllData" />
        </px-tooltip>
      </div>
    </template> -->
  <div class="workbench-content">
    <fabBoardEchartsModelBoxItem
      ref="workbenchCountRef"
      exportImage
      echartsType="bar"
      unit="台"
      :title="workbenchCountTitle"
      :data="workbenchCountData"
    />
    <fabBoardEchartsModelBoxItem
      ref="workbenchStatusRef"
      exportImage
      echartsType="pie"
      eventType="eqpStatus"
      unit="台"
      :title="workbenchStatusTitle"
      :name="workbenchStatusTitle"
      :data="workbenchStatusData"
    />
    <fabBoardEchartsModelBoxItem
      ref="workbenchPMTaskRef"
      exportImage
      echartsType="pie"
      eventType="pmTask"
      unit="台"
      :title="workbenchPMTaskTitle"
      :name="workbenchPMTaskTitle"
      :data="workbenchPMTaskData"
    />
    <fabBoardEchartsModelBoxItem
      ref="workbenchMaintainTaskRef"
      exportImage
      echartsType="pie"
      eventType="repairTask"
      unit="台"
      :title="workbenchMaintainTaskTitle"
      :name="workbenchMaintainTaskTitle"
      :data="workbenchMaintainTaskData"
    />
    <fabBoardEchartsModelBoxItem
      ref="workbenchAlarmRef"
      exportImage
      echartsType="pie"
      eventType="abnormalAlarm"
      unit="台"
      :title="workbenchAlarmTitle"
      :name="workbenchAlarmTitle"
      :data="workbenchAlarmData"
    />
  </div>
  <!-- </fabBoardModelBox> -->
</template>

<style lang="scss" scoped>
.workbench-content {
  display: grid;
  // grid-template-rows: repeat(1, 100%);
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
  width: 100%;
  height: v-bind(module_height);
}
</style>
